package com.bw.i_video.startup

import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.os.Process
import android.util.Log
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

/**
 * 启动优化工具类
 * 提供各种启动优化的辅助方法
 */
object StartupUtils {
    
    private const val TAG = "StartupUtils"
    
    /**
     * 获取设备内存信息
     */
    fun getDeviceMemoryInfo(context: Context): DeviceMemoryInfo {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        
        return DeviceMemoryInfo(
            totalMemory = memoryInfo.totalMem,
            availableMemory = memoryInfo.availMem,
            threshold = memoryInfo.threshold,
            lowMemory = memoryInfo.lowMemory
        )
    }
    
    /**
     * 获取进程内存信息
     */
    fun getProcessMemoryInfo(context: Context): ProcessMemoryInfo {
        val pid = Process.myPid()
        val memoryPid = IntArray(1)
        memoryPid[0] = pid
        
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = activityManager.getProcessMemoryInfo(memoryPid)
        
        return if (memoryInfo.isNotEmpty()) {
            val memory = memoryInfo[0]
            ProcessMemoryInfo(
                pid = pid,
                totalPss = memory.totalPss,
                totalUss = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    try {
                        memory.javaClass.getMethod("getTotalUss").invoke(memory) as? Int ?: 0
                    } catch (e: Exception) {
                        0
                    }
                } else {
                    0
                },
                totalRss = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    try {
                        memory.javaClass.getMethod("getTotalRss").invoke(memory) as? Int ?: 0
                    } catch (e: Exception) {
                        0
                    }
                } else {
                    0
                }
            )
        } else {
            ProcessMemoryInfo(pid, 0, 0, 0)
        }
    }
    
    /**
     * 获取CPU信息
     */
    fun getCpuInfo(): CpuInfo {
        var cpuCount = 0
        var cpuFreq = 0L
        
        try {
            // 获取CPU核心数
            cpuCount = Runtime.getRuntime().availableProcessors()
            
            // 获取CPU频率
            val reader = BufferedReader(FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"))
            cpuFreq = reader.readLine().toLong()
            reader.close()
        } catch (e: IOException) {
            Log.w(TAG, "获取CPU信息失败", e)
        }
        
        return CpuInfo(
            coreCount = cpuCount,
            frequency = cpuFreq
        )
    }
    
    /**
     * 检查是否为低端设备
     */
    fun isLowEndDevice(context: Context): Boolean {
        val memoryInfo = getDeviceMemoryInfo(context)
        val cpuInfo = getCpuInfo()
        
        // 内存小于2GB或CPU核心数小于4认为是低端设备
        return memoryInfo.totalMemory < 2 * 1024 * 1024 * 1024L || cpuInfo.coreCount < 4
    }
    
    /**
     * 获取设备性能等级
     */
    fun getDevicePerformanceLevel(context: Context): DevicePerformanceLevel {
        return when {
            isLowEndDevice(context) -> DevicePerformanceLevel.LOW
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> DevicePerformanceLevel.HIGH
            else -> DevicePerformanceLevel.MEDIUM
        }
    }
    
    /**
     * 根据设备性能调整启动优化策略
     */
    fun adjustStartupStrategy(context: Context): StartupStrategy {
        val performanceLevel = getDevicePerformanceLevel(context)
        
        return when (performanceLevel) {
            DevicePerformanceLevel.LOW -> {
                StartupStrategy(
                    enableParallelExecution = false,
                    threadPoolSize = 2,
                    startupTimeout = 8000L,
                    enablePreload = false
                )
            }
            DevicePerformanceLevel.MEDIUM -> {
                StartupStrategy(
                    enableParallelExecution = true,
                    threadPoolSize = 3,
                    startupTimeout = 6000L,
                    enablePreload = true
                )
            }
            DevicePerformanceLevel.HIGH -> {
                StartupStrategy(
                    enableParallelExecution = true,
                    threadPoolSize = 4,
                    startupTimeout = 5000L,
                    enablePreload = true
                )
            }
        }
    }
    
    /**
     * 记录启动性能指标
     */
    fun recordStartupMetrics(context: Context, startupTime: Long) {
        val memoryInfo = getDeviceMemoryInfo(context)
        val processInfo = getProcessMemoryInfo(context)
        val cpuInfo = getCpuInfo()
        
        Log.d(TAG, """
            启动性能指标:
            - 启动时间: ${startupTime}ms
            - 设备内存: ${memoryInfo.totalMemory / (1024 * 1024)}MB
            - 可用内存: ${memoryInfo.availableMemory / (1024 * 1024)}MB
            - 进程内存: ${processInfo.totalPss / 1024}KB
            - CPU核心数: ${cpuInfo.coreCount}
            - CPU频率: ${cpuInfo.frequency / 1000}MHz
        """.trimIndent())
    }
}

/**
 * 设备内存信息
 */
data class DeviceMemoryInfo(
    val totalMemory: Long,
    val availableMemory: Long,
    val threshold: Long,
    val lowMemory: Boolean
)

/**
 * 进程内存信息
 */
data class ProcessMemoryInfo(
    val pid: Int,
    val totalPss: Int,
    val totalUss: Int,
    val totalRss: Int
)

/**
 * CPU信息
 */
data class CpuInfo(
    val coreCount: Int,
    val frequency: Long
)

/**
 * 设备性能等级
 */
enum class DevicePerformanceLevel {
    LOW, MEDIUM, HIGH
}

/**
 * 启动优化策略
 */
data class StartupStrategy(
    val enableParallelExecution: Boolean,
    val threadPoolSize: Int,
    val startupTimeout: Long,
    val enablePreload: Boolean
)
